
import { useState } from 'react'
import { useDroppable } from '@dnd-kit/core'
import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable'
import { Plus, MoreHorizontal, X, Check } from 'lucide-react'
import { Task, TaskStatus, KanbanColumn as KanbanColumnType } from '../types'
import KanbanTaskCard from './KanbanTaskCard'

interface KanbanColumnProps {
  column: KanbanColumnType
  tasks: Task[]
  onTaskClick: (taskId: string) => void
  onDeleteTask?: (taskId: string) => void
  onAddTask?: (status: TaskStatus, title: string) => void
  onRenameColumn?: (columnId: string, newTitle: string) => void
  onClearColumn?: (columnId: string) => void
  onColumnSettings?: (columnId: string) => void
  onMoveTaskToColumn?: (taskId: string, newStatus: string) => void
  availableColumns?: Array<{id: string, title: string, status: string, color: string}>
  isMobileView?: boolean
}

export default function KanbanColumn({ 
  column, 
  tasks, 
  onTaskClick, 
  onDeleteTask, 
  onAddTask, 
  onRenameColumn, 
  onClearColumn, 
  onColumnSettings,
  onMoveTaskToColumn,
  availableColumns,
  isMobileView
}: KanbanColumnProps) {
  const [isAddingTask, setIsAddingTask] = useState(false)
  const [newTaskTitle, setNewTaskTitle] = useState('')
  const [showColumnMenu, setShowColumnMenu] = useState(false)
  const [isRenamingColumn, setIsRenamingColumn] = useState(false)
  const [newColumnTitle, setNewColumnTitle] = useState(column.title)
  
  const { setNodeRef, isOver } = useDroppable({
    id: column.status,
    data: {
      type: 'column',
      status: column.status
    }
  })

  const taskIds = tasks.map(task => task.id)

  const getColumnStyle = (status: TaskStatus) => {
    const baseStyle = "bg-theme-bg-secondary border-2 border-dashed rounded-lg"
    switch (status) {
      case 'todo':
        return `${baseStyle} border-theme-border ${isOver ? 'border-slate-400 bg-theme-bg-tertiary' : ''}`
      case 'in_progress':
        return `${baseStyle} border-blue-300 ${isOver ? 'border-blue-400 bg-blue-50' : ''}`
      case 'review':
        return `${baseStyle} border-orange-300 ${isOver ? 'border-orange-400 bg-orange-50' : ''}`
      case 'done':
        return `${baseStyle} border-green-300 ${isOver ? 'border-green-400 bg-green-50' : ''}`
      default:
        return `${baseStyle} border-theme-border`
    }
  }

  const getHeaderColor = (status: TaskStatus) => {
    switch (status) {
      case 'todo':
        return 'bg-theme-bg-tertiary text-theme-text border-theme-border'
      case 'in_progress':
        return 'bg-blue-100 text-blue-800 border-blue-200'
      case 'review':
        return 'bg-orange-100 text-orange-800 border-orange-200'
      case 'done':
        return 'bg-green-100 text-green-800 border-green-200'
      default:
        return 'bg-theme-bg-tertiary text-theme-text border-theme-border'
    }
  }

  const handleAddTask = () => {
    setIsAddingTask(true)
  }

  const handleSaveTask = () => {
    if (newTaskTitle.trim() && onAddTask) {
      onAddTask(column.status, newTaskTitle.trim())
      setNewTaskTitle('')
      setIsAddingTask(false)
    }
  }

  const handleCancelAdd = () => {
    setNewTaskTitle('')
    setIsAddingTask(false)
  }

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleSaveTask()
    } else if (e.key === 'Escape') {
      handleCancelAdd()
    }
  }

  const handleColumnSettings = () => {
    setShowColumnMenu(!showColumnMenu)
  }

  const handleHideColumn = () => {
    if (onColumnSettings) {
      onColumnSettings(column.id)
    }
    setShowColumnMenu(false)
  }

  const handleStartRename = () => {
    setIsRenamingColumn(true)
    setNewColumnTitle(column.title)
    setShowColumnMenu(false)
  }

  const handleSaveRename = () => {
    if (newColumnTitle.trim() && onRenameColumn) {
      onRenameColumn(column.id, newColumnTitle.trim())
    }
    setIsRenamingColumn(false)
  }

  const handleCancelRename = () => {
    setNewColumnTitle(column.title)
    setIsRenamingColumn(false)
  }

  const handleRenameKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleSaveRename()
    } else if (e.key === 'Escape') {
      handleCancelRename()
    }
  }

  const handleClearColumn = () => {
    if (tasks.length === 0) {
      setShowColumnMenu(false)
      return
    }
    
    if (confirm(`确定要清空"${column.title}"列中的所有 ${tasks.length} 个任务吗？此操作不可撤销。`)) {
      if (onClearColumn) {
        onClearColumn(column.id)
      }
    }
    setShowColumnMenu(false)
  }

  return (
    <div className="flex flex-col h-full w-full min-h-[70vh] md:min-h-96">
      {/* 列头 */}
      <div className={`
        flex items-center justify-between p-3 rounded-t-lg border
        ${getHeaderColor(column.status)}
      `}>
        <div className="flex items-center gap-2 flex-1 min-w-0">
          <div 
            className="w-3 h-3 rounded-full flex-shrink-0"
            style={{ backgroundColor: column.color }}
          />
          {isRenamingColumn ? (
            <div className="flex items-center gap-1 flex-1">
              <input
                type="text"
                value={newColumnTitle}
                onChange={(e) => setNewColumnTitle(e.target.value)}
                onKeyDown={handleRenameKeyPress}
                className="flex-1 px-2 py-1 text-sm font-semibold bg-white border border-blue-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
                autoFocus
              />
              <button
                onClick={handleSaveRename}
                className="p-1 text-green-600 hover:bg-green-100 rounded"
                title="保存"
              >
                <Check size={14} />
              </button>
              <button
                onClick={handleCancelRename}
                className="p-1 text-red-600 hover:bg-red-100 rounded"
                title="取消"
              >
                <X size={14} />
              </button>
            </div>
          ) : (
            <h3 className="font-semibold text-sm truncate">
              {column.title}
            </h3>
          )}
          <span className="px-2 py-1 bg-theme-bg/50 rounded-full text-xs font-medium flex-shrink-0">
            {column.taskCount}
          </span>
        </div>

        <div className="flex items-center gap-1">
          {/* 添加任务按钮 */}
          <button
            onClick={handleAddTask}
            className="p-1.5 hover:bg-blue-100 hover:text-blue-600 rounded-lg transition-all duration-200 group"
            title="添加任务"
          >
            <Plus className="w-4 h-4 group-hover:scale-110 transition-transform" />
          </button>

          {/* 列设置按钮 */}
          <div className="relative">
            <button
              onClick={handleColumnSettings}
              className="p-1 hover:bg-theme-bg/50 rounded transition-colors"
              title="列设置"
            >
              <MoreHorizontal className="w-4 h-4" />
            </button>
            
            {/* 列设置菜单 */}
            {showColumnMenu && (
              <div className="absolute right-0 top-8 bg-white border border-gray-200 rounded-lg shadow-lg z-[60] min-w-[140px]">
                <div className="p-2">
                  <div className="text-xs font-medium text-gray-500 mb-2">{column.title} 设置</div>
                  <button
                    onClick={handleStartRename}
                    className="w-full flex items-center gap-2 px-2 py-1.5 text-sm text-gray-700 hover:bg-gray-50 rounded"
                  >
                    ✏️ 重命名列
                  </button>
                  <button
                    onClick={handleClearColumn}
                    disabled={tasks.length === 0}
                    className={`w-full flex items-center gap-2 px-2 py-1.5 text-sm rounded ${
                      tasks.length === 0 
                        ? 'text-gray-400 cursor-not-allowed' 
                        : 'text-red-600 hover:bg-red-50'
                    }`}
                  >
                    🗑️ 清空列 {tasks.length > 0 && `(${tasks.length})`}
                  </button>
                  <button
                    onClick={handleHideColumn}
                    className="w-full flex items-center gap-2 px-2 py-1.5 text-sm text-gray-700 hover:bg-gray-50 rounded"
                  >
                    👁️ 隐藏列
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 任务列表区域 */}
      <div
        ref={setNodeRef}
        className={`
          flex-1 p-3 min-h-80 sm:min-h-96 lg:min-h-[32rem] overflow-y-auto
          ${getColumnStyle(column.status)}
          ${isOver ? 'ring-2 ring-offset-2' : ''}
        `}
      >
        {tasks.length === 0 && !isAddingTask ? (
          <div className="flex flex-col items-center justify-center h-32 text-slate-400">
            <div className="text-3xl mb-3 opacity-60">
              {column.status === 'todo' && '📝'}
              {column.status === 'in_progress' && '⚡'}
              {column.status === 'review' && '👀'}
              {column.status === 'done' && '✅'}
            </div>
            <p className="text-sm text-center mb-3 text-slate-500">
              {column.status === 'todo' && '还没有待处理的任务'}
              {column.status === 'in_progress' && '还没有进行中的任务'}
              {column.status === 'review' && '还没有待审核的任务'}
              {column.status === 'done' && '还没有完成的任务'}
            </p>
            <div className="text-xs text-slate-400 flex items-center gap-1">
              <span>点击右上角</span>
              <div className="inline-flex items-center justify-center w-4 h-4 bg-slate-200 rounded text-slate-500">
                <Plus size={10} />
              </div>
              <span>添加任务</span>
            </div>
          </div>
        ) : (
          <SortableContext items={taskIds} strategy={verticalListSortingStrategy}>
            <div className="space-y-2">
              {tasks.map((task) => (
                <KanbanTaskCard
                  key={task.id}
                  task={task}
                  onClick={onTaskClick}
                  onDelete={onDeleteTask}
                  onMoveToColumn={onMoveTaskToColumn}
                  availableColumns={availableColumns}
                  isMobileView={isMobileView}
                />
              ))}
            </div>
          </SortableContext>
        )}

        {/* 快速添加任务 */}
        {onAddTask && (isAddingTask || tasks.length > 0) && (
          <div className="mt-3 pt-3 border-t border-theme-border/30">
            {isAddingTask ? (
              <div className="bg-theme-bg border border-theme-border rounded-lg p-3 space-y-2">
                <input
                  type="text"
                  value={newTaskTitle}
                  onChange={(e) => setNewTaskTitle(e.target.value)}
                  onKeyDown={handleKeyPress}
                  placeholder="输入任务标题..."
                  className="w-full px-3 py-2 text-sm border border-theme-border rounded focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  autoFocus
                />
                <div className="flex items-center gap-2">
                  <button
                    onClick={handleSaveTask}
                    disabled={!newTaskTitle.trim()}
                    className="flex items-center gap-1 px-3 py-1.5 text-xs bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                  >
                    <Check size={14} />
                    添加
                  </button>
                  <button
                    onClick={handleCancelAdd}
                    className="flex items-center gap-1 px-3 py-1.5 text-xs border border-theme-border rounded hover:bg-theme-bg-secondary transition-colors"
                  >
                    <X size={14} />
                    取消
                  </button>
                </div>
              </div>
            ) : (
              <button
                onClick={handleAddTask}
                className="w-full flex items-center justify-center gap-2 py-2 text-sm text-theme-text-secondary border border-dashed border-theme-border rounded-lg hover:border-blue-400 hover:text-blue-600 hover:bg-blue-50/50 transition-all group"
              >
                <Plus size={16} className="group-hover:scale-110 transition-transform" />
                添加任务
              </button>
            )}
          </div>
        )}
      </div>
    </div>
  )
}
